package com.usb.serial.device;

import android.Manifest;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;


import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;

import android.telephony.TelephonyManager;
import android.util.Base64;

import android.util.Log;


import android.view.MotionEvent;
import android.view.View;

import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;

import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.usb.serial.device.javaBean.InfoBean;
import com.usb.serial.device.retrofit.ApiService;
import com.usb.serial.device.retrofit.RetrofitClient;
import com.usb.serial.device.settingIp.SettingIpActivity;
import com.usb.serial.device.settingIp.Url;
import com.usb.serial.device.util.MyOkHttp;
import com.usb.serial.device.util.Permission;
import com.usb.serial.device.util.SnModelUtil;
import com.usb.serial.device.util.SnowflakeIdGenerator;
import com.usb.serial.device.util.ThreadPool;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.net.Socket;
import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;

import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;


import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.core.SingleObserver;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.BufferedSource;
import okio.ByteString;
import retrofit2.Call;
import retrofit2.Retrofit;

import static com.usb.serial.device.SerialUtils.ByteArrToHex;

public class MainActivity extends AppCompatActivity {
    String byteArrToHex = "";
    private SerialControl serialControl;
    private String submit = "http://" + URL.getIP() + /*192.168.1.98:8582*/"/api/addCradData";
    private String 提交 = "http://" + URL.getIP() + "/api/submit";
    private String url = "http://" +  URL.getIP() + "/api/appData";
    private String yanzheng = "http://" + URL.getIP() + "/api/yanzheng";
    private EditText editText;
    private ProgressDialog progressDialog;
    private TimeChangedReceiver timeChangedReceiver;
    private int secondsPassed;
    private ImageView icHand;
    private ConstraintLayout cl;
    private Button btn_site_visit, btn_in, btn_out, btn_lunch, btn_meeting, btn_phone, btn_pto, btn_break, ok;
    private TextView ll_text_birthDate1, nam1, sex1, ll_text_passportNo, ll_text_company, ll_text_department, ll_text_cardId, tvTime, tvDate;
    private final Gson gson = new Gson();
    private static final int REQUEST_READ_PHONE_STATE = 1;
    private InfoBean infoBean;
    private String stateId, imei1, state;
    private Socket socket;
    private String result;
    private Request request;
    private OkHttpClient client;
    private WebSocket ws;
    private CheckBox isFire;
    private Boolean flag = false;
    private Boolean flag1 = false;
    private boolean abc;
    private TextView one;
    private long decimalNumber;
    private ConstraintLayout title;
    private TextView titleTv;

    private TextView settingIp;

    private Boolean er1 = false;
    @SuppressLint("MissingPermission")
    private String no;
    private TextView title_content;

    public SnowflakeIdGenerator snowflakeIdGenerator = new SnowflakeIdGenerator(1);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        mBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(R.layout.activity_main/*mBinding.getRoot()*/);
        timeChangedReceiver = new TimeChangedReceiver();

        Url.context = this;

        //获取设备的序列号
        no = Build.SERIAL;

        Log.d("序列号", "no: " +no);

        //动态获取权限
        boolean grantExternalRW = Permission.isGrantExternalRW(this, 1);

        //获取设备的sn码
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查运行时权限
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                // 没有权限，请求权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE);
            } else {
                // 已经有权限，直接获取IMEI号码
                getIMEI();
            }
        } else {
            // Android版本低于6.0，直接获取IMEI号码
            getIMEI();
        }

        //初始化控件
        initView();
        //初始化刷卡硬件
        initSerialHelper();

        settingIp.setOnClickListener(v -> {

            startActivity(new Intent(this, SettingIpActivity.class));

        });

    }

    //获取sn码的逻辑
    private void getIMEI() {
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager != null) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    String imei1 = telephonyManager.getImei(0); // 获取SIM卡槽1的IMEI号码
                } else {
                    imei1 = SnModelUtil.xx(this);
                    Log.d("sn", "sn: " +imei1);
                }
            }
        }
    }

    //网络权限回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_READ_PHONE_STATE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 获取权限成功
                getIMEI();
            } else {
            }
        }
    }

    //数据渲染逻辑
    private void setData(InfoBean infoBean) {
        runOnUiThread(() -> {
            canDialog();
            title_content.setText(infoBean.getName());
            nam1.setText(infoBean.getName());
            sex1.setText(infoBean.getGender());
            ll_text_passportNo.setText(infoBean.getNo());
            ll_text_company.setText(infoBean.getCompany());
            ll_text_department.setText(infoBean.getDepar());
            ll_text_cardId.setText(infoBean.getId());
            ll_text_birthDate1.setText(infoBean.getWarehousename());
            cl.setVisibility(View.GONE);

            try {
                byte[] imageBytes = Base64.decode(infoBean.getImage(), Base64.DEFAULT);
                Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
                icHand.setImageBitmap(bitmap);
            }catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    //清空页面数据
    private void cleanData() {
        try {
            Thread.sleep(1000 * 2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        title_content.setText("Access control");
        icHand.setImageResource(R.mipmap.add);
        nam1.setText("");
        sex1.setText("");
        ll_text_passportNo.setText("");
        ll_text_company.setText("");
        ll_text_department.setText("");
        ll_text_cardId.setText("");
        ll_text_birthDate1.setText("");
        editText.setText("");
    }


    //初始化控件
    private void initView() {
        setTitle("门禁");
        editText = findViewById(R.id.auto_text_view);
        title_content = findViewById(R.id.title_content);
        title = findViewById(R.id.title);
        titleTv = findViewById(R.id.title_content);

        ok = findViewById(R.id.ok);
        one = findViewById(R.id.one);


        cl = findViewById(R.id.go_image);
        settingIp = findViewById(R.id.setting_ip);
        nam1 = findViewById(R.id.ll_text_name);
        sex1 = findViewById(R.id.ll_text_sex);
        ll_text_passportNo = findViewById(R.id.ll_text_passportNo);
        ll_text_company = findViewById(R.id.ll_text_company);
        ll_text_department = findViewById(R.id.ll_text_department);
        ll_text_cardId = findViewById(R.id.ll_text_CardId);
        ll_text_birthDate1 = findViewById(R.id.ll_text_birthDate);
        icHand = findViewById(R.id.imageView);
        isFire = findViewById(R.id.is_fire);

        tvDate = findViewById(R.id.tv_date);
        tvTime = findViewById(R.id.tv_time);

        title_content.setOnClickListener(v-> {

            post("1", "1");

        });

        //这个是定时器  实时的去更新 时间   和   日期
        ThreadPool.runThread(() -> {
            //开一个定时任务
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    // 更新UI需要在主线程进行
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            secondsPassed++;
                            tvTime.setText(new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH).format(new Date()));
                            tvDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                        }
                    });
                }
            }, 0, 1000); // 在0ms后开始执行任务，每隔1000ms执行一次
        });
    }

    //刷卡请求
    @SuppressLint("CheckResult")
    private void post(String carId, String snCode) {

        showDialog("Loading...");
        Map<String, String> map = new HashMap<>();
        map.put("idNo", carId);
        map.put("sncode", snCode);

        Retrofit retrofit1 = RetrofitClient.getRetrofit("http://" + Url.getIP()[0] + ":8581");
        Retrofit retrofit2 = RetrofitClient.getRetrofit("http://" + Url.getIP()[1] + ":8581");
        Retrofit retrofit3 = RetrofitClient.getRetrofit("http://" + Url.getIP()[2] + ":8581");
        Retrofit retrofit4 = RetrofitClient.getRetrofit("http://" + Url.getIP()[3] + ":8581");
        Retrofit retrofit5 = RetrofitClient.getRetrofit("http://" + Url.getIP()[4] + ":8581");

        ApiService apiService1 = retrofit1.create(ApiService.class);
        ApiService apiService2 = retrofit2.create(ApiService.class);
        ApiService apiService3 = retrofit3.create(ApiService.class);
        ApiService apiService4 = retrofit4.create(ApiService.class);
        ApiService apiService5 = retrofit5.create(ApiService.class);

// 使用 onErrorResumeNext 为每个 getData 调用添加错误处理
        Observable<ResponseBody> observable1 = apiService1.getData(map.get("idNo"), map.get("sncode"))
                .onErrorResumeNext(throwable -> Observable.just(new ResponseBody() {
                    @Override
                    public MediaType contentType() {
                        return null;
                    }

                    @Override
                    public long contentLength() {
                        return 0;
                    }

                    @Override
                    public BufferedSource source() {
                        return null;
                    }
                })); // 失败时返回默认 ResponseBody

        Observable<ResponseBody> observable2 = apiService2.getData(map.get("idNo"), map.get("sncode"))
                .onErrorResumeNext(throwable -> Observable.just(new ResponseBody() {
                    @Override
                    public MediaType contentType() {
                        return null;
                    }

                    @Override
                    public long contentLength() {
                        return 0;
                    }

                    @Override
                    public BufferedSource source() {
                        return null;
                    }
                }));

        Observable<ResponseBody> observable3 = apiService3.getData(map.get("idNo"), map.get("sncode"))
                .onErrorResumeNext(throwable -> Observable.just(new ResponseBody() {
                    @Override
                    public MediaType contentType() {
                        return null;
                    }

                    @Override
                    public long contentLength() {
                        return 0;
                    }

                    @Override
                    public BufferedSource source() {
                        return null;
                    }
                }));

        Observable<ResponseBody> observable4 = apiService4.getData(map.get("idNo"), map.get("sncode"))
                .onErrorResumeNext(throwable -> Observable.just(new ResponseBody() {
                    @Override
                    public MediaType contentType() {
                        return null;
                    }

                    @Override
                    public long contentLength() {
                        return 0;
                    }

                    @Override
                    public BufferedSource source() {
                        return null;
                    }
                }));

        Observable<ResponseBody> observable5 = apiService5.getData(map.get("idNo"), map.get("sncode"))
                .onErrorResumeNext(throwable -> Observable.just(new ResponseBody() {
                    @Override
                    public MediaType contentType() {
                        return null;
                    }

                    @Override
                    public long contentLength() {
                        return 0;
                    }

                    @Override
                    public BufferedSource source() {
                        return null;
                    }
                }));


        List<Observable<ResponseBody>> observables = Arrays.asList(
                observable1,
                observable2,
                observable3,
                observable4,
                observable5
                // ... 其他 ApiService 的 Observable
        );

        Observable<ResponseBody> mergedObservable = Observable.merge(observables);

        mergedObservable.toList().subscribe(new SingleObserver<List<ResponseBody>>() {
            @Override
            public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

            }

            @Override
            public void onSuccess(@io.reactivex.rxjava3.annotations.NonNull List<ResponseBody> responseBodies) {
                Log.d("分发", "onSuccess: " + responseBodies.size() + " responses received.");
                try {
//                    String result1 = responseBodies.get(0).string();
//                    String result2 = responseBodies.get(1).string();
//                    String result3 = responseBodies.get(2).string();
//                    String result4 = responseBodies.get(3).string();
//                    String result5 = responseBodies.get(4).string();
//                    Log.d("刷卡分发", "第一个：" + result1 + ", 第二个：" +result2 + ", 第三个：" + result3 + ", 第四个：" + result4 + ", 第五个：" + result5);
//                    if ((responseBodies.get(0) != null) && (responseBodies.get(0).string() != null)) {
//                        Log.d("mes: " , responseBodies.get(0).toString());
//
//                        String result1 = responseBodies.get(0).string();
//                        newSubmit(result1);
//                    }
//                    else if (result2.isEmpty()) {
//                        newSubmit(result2);
//                    }else if (result3.isEmpty()) {
//                        newSubmit(result3);
//                    }else if (result4.isEmpty()) {
//                        newSubmit(result4);
//                    }else if (result5.isEmpty()) {
//                        newSubmit(result5);
//                    }
                    if (responseBodies.get(0).contentLength() != 0) {
                        String result1 = responseBodies.get(0).string();
                        newSubmit(result1);
                    }else if (responseBodies.get(1).contentLength() != 0) {
                        String result2 = responseBodies.get(1).string();
                        newSubmit(result2);
                    }else if (responseBodies.get(2).contentLength() != 0) {
                        String result3 = responseBodies.get(2).string();
                        newSubmit(result3);
                    }else if (responseBodies.get(3).contentLength() != 0) {
                        String result4 = responseBodies.get(3).string();
                        newSubmit(result4);
                    }else if (responseBodies.get(4).contentLength() != 0) {
                        String result5 = responseBodies.get(4).string();
                        newSubmit(result5);
                    }else {
                        canDialog();
                        showToast("Please Check whether IP is correct.");
                    }

                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            }

            @Override
            public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                Log.d("分发", "onError: " + e.getMessage());
                canDialog();
            }
        });


//        /**
//         * 首先先请求 192.168.1.98:8582 这个服务
//         * */
//        MyOkHttp.getInstance().post(url, map, new MyOkHttp.requestMessage() {
//            @Override
//            public void requestFail() {
//
//                //失败了提示 重新连接服务器
//                runOnUiThread(() -> {
//                    Toast.makeText(MainActivity.this, "Attempt to switch servers", Toast.LENGTH_SHORT).show();
//                });
//
//                //接着请求另外一台服务器
//                MyOkHttp.getInstance().post("http://192.168.1.96:8582/api/appData", map, new MyOkHttp.requestMessage() {
//                    @Override
//                    public void requestFail() {
//                        //这个服务器也失败
//                        runOnUiThread(() -> {
//                            //停止一秒中后提示连接服务器失败
//                            try {
//                                Thread.sleep(1000);
//                            }catch (Exception e) {
//
//                            }
//                            Toast.makeText(MainActivity.this, "Failed to connect to server", Toast.LENGTH_SHORT).show();
//                        });
//                        //然后关闭弹窗
//                        canDialog();
//                    }
//
//                    @Override
//                    public void requestComplete() {
//
//                    }
//
//                    @Override
//                    public void requestSuccess(Response response) throws IOException {
//                        String result = response.body().string();
//                        Log.d("jiangjianhua", "result: " + result);
//                        if (result.isEmpty() || "{}".equals(result)) {
//                            runOnUiThread(() -> {
//                                Toast.makeText(MainActivity.this, "Unable to find this person", Toast.LENGTH_SHORT).show();
//                            });
//                        } else {
//                            Log.d("jiangjianhua", "刷卡拿到的数据: " + result);
//                            infoBean = gson.fromJson(result, InfoBean.class);
//                            runOnUiThread(() -> {
//                                submit();
//                                setData(infoBean);
//                            });
//
//                        }
//                    }
//                });
//
//
//            }
//
//            @Override
//            public void requestComplete() {
//
//            }
//
//            @Override
//            public void requestSuccess(Response response) throws IOException {
//                String result = response.body().string();
//                Log.d("这个是什么", "result: " +result);
//                if (result.isEmpty()) {
//                    runOnUiThread(() -> {
//                        Toast.makeText(MainActivity.this, "Unable to find this person", Toast.LENGTH_SHORT).show();
//                    });
//                } else {
//                    Log.d("jiangjianhua", "刷卡拿到的数据: " + result);
//                    infoBean = gson.fromJson(result, InfoBean.class);
//                    runOnUiThread(() -> {
//                        //新家的
//                        canDialog();
//                        setData(infoBean);
//                        submit();
//
//
//                    });
//
//                }
//            }
//        });
    }

    private void newSubmit(String result) {

        Log.d("message", result);

        if (result.isEmpty() || result.equals("{}")) {
            canDialog();
            showToast("No such person found. Please try again.");
            return;
        }
        infoBean = gson.fromJson(result, InfoBean.class);

        //TODO: 数据渲染

        setData(infoBean);

        Log.d("这个是数据转换", "newSubmit: " + infoBean);


        Map<String, String> map = new HashMap<>();
        map.put("warehouseCode", infoBean.getWarehouseCode());
        map.put("status", stateId == null ? "" : stateId);
        map.put("idNo", decimalNumber + "");
        map.put("sncode", no);

        //提交

        Retrofit retrofit1 = RetrofitClient.getRetrofit("http://" + Url.getIP()[0] + ":8581");
        Retrofit retrofit2 = RetrofitClient.getRetrofit("http://" + Url.getIP()[1] + ":8581");
        Retrofit retrofit3 = RetrofitClient.getRetrofit("http://" + Url.getIP()[2] + ":8581");
        Retrofit retrofit4 = RetrofitClient.getRetrofit("http://" + Url.getIP()[3] + ":8581");
        Retrofit retrofit5 = RetrofitClient.getRetrofit("http://" + Url.getIP()[4] + ":8581");

        ApiService apiService1 = retrofit1.create(ApiService.class);
        ApiService apiService2 = retrofit2.create(ApiService.class);
        ApiService apiService3 = retrofit3.create(ApiService.class);
        ApiService apiService4 = retrofit4.create(ApiService.class);
        ApiService apiService5 = retrofit5.create(ApiService.class);

        //随机ID 18位
        String idStr = "";
        idStr = snowflakeIdGenerator.nextId();
        Log.d("idStr = ", idStr);

        Observable<ResponseBody> observable1 = apiService1.submit(map.get("warehouseCode"), map.get("status"), map.get("idNo"), map.get("sncode"), idStr)
                .onErrorResumeNext(throwable -> Observable.just(new ResponseBody() {
                    @Override
                    public MediaType contentType() {
                        return null;
                    }

                    @Override
                    public long contentLength() {
                        return 0;
                    }

                    @Override
                    public BufferedSource source() {
                        return null;
                    }
                }));
        Observable<ResponseBody> observable2 = apiService2.submit(map.get("warehouseCode"), map.get("status"), map.get("idNo"), map.get("sncode"), idStr)
                .onErrorResumeNext(throwable -> Observable.just(new ResponseBody() {
                    @Override
                    public MediaType contentType() {
                        return null;
                    }

                    @Override
                    public long contentLength() {
                        return 0;
                    }

                    @Override
                    public BufferedSource source() {
                        return null;
                    }
                }));
        Observable<ResponseBody> observable3 = apiService3.submit(map.get("warehouseCode"), map.get("status"), map.get("idNo"), map.get("sncode"), idStr)
                .onErrorResumeNext(throwable -> Observable.just(new ResponseBody() {
                    @Override
                    public MediaType contentType() {
                        return null;
                    }

                    @Override
                    public long contentLength() {
                        return 0;
                    }

                    @Override
                    public BufferedSource source() {
                        return null;
                    }
                }));
        Observable<ResponseBody> observable4 = apiService4.submit(map.get("warehouseCode"), map.get("status"), map.get("idNo"), map.get("sncode"), idStr)
                .onErrorResumeNext(throwable -> Observable.just(new ResponseBody() {
                    @Override
                    public MediaType contentType() {
                        return null;
                    }

                    @Override
                    public long contentLength() {
                        return 0;
                    }

                    @Override
                    public BufferedSource source() {
                        return null;
                    }
                }));
        Observable<ResponseBody> observable5 = apiService5.submit(map.get("warehouseCode"), map.get("status"), map.get("idNo"), map.get("sncode"), idStr)
                .onErrorResumeNext(throwable -> Observable.just(new ResponseBody() {
                    @Override
                    public MediaType contentType() {
                        return null;
                    }

                    @Override
                    public long contentLength() {
                        return 0;
                    }

                    @Override
                    public BufferedSource source() {
                        return null;
                    }
                }));


        List<Observable<ResponseBody>> observables = Arrays.asList(
                observable1,
                observable2,
                observable3,
                observable4,
                observable5
                // ... 其他 ApiService 的 Observable
        );

        Observable<ResponseBody> mergedObservable = Observable.merge(observables);

        mergedObservable.toList().subscribe(new SingleObserver<List<ResponseBody>>() {
            @Override
            public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

            }

            @Override
            public void onSuccess(@io.reactivex.rxjava3.annotations.NonNull List<ResponseBody> responseBodies) {
                Log.d("分发", "onSuccess: " + responseBodies.size() + " responses received.");
                try {
//                    String result1 = responseBodies.get(0).string();
//                    String result2 = responseBodies.get(1).string();
//                    String result3 = responseBodies.get(2).string();
//                    String result4 = responseBodies.get(3).string();
//                    String result5 = responseBodies.get(4).string();
//                    Log.d("刷卡分发", "第一个：" + result1 + ", 第二个：" +result2 + ", 第三个：" + result3 + ", 第四个：" + result4 + ", 第五个：" + result5);
//                    if (!result1.isEmpty()) {
//                        mySuccess(result1);
//                    }else if (result2.isEmpty()) {
//                        mySuccess(result2);
//                    }else if (result3.isEmpty()) {
//                        mySuccess(result3);
//                    }else if (result4.isEmpty()) {
//                        mySuccess(result4);
//                    }else if (result5.isEmpty()) {
//                        mySuccess(result5);
//                    }
                    if (responseBodies.get(0).contentLength() != 0) {
                        String result1 = responseBodies.get(0).string();
                        mySuccess(result1);
                    }else if (responseBodies.get(1).contentLength() != 0) {
                        String result2 = responseBodies.get(1).string();
                        mySuccess(result2);
                    }else if (responseBodies.get(2).contentLength() != 0) {
                        String result3 = responseBodies.get(2).string();
                        mySuccess(result3);
                    }else if (responseBodies.get(3).contentLength() != 0) {
                        String result4 = responseBodies.get(3).string();
                        mySuccess(result4);
                    }else if (responseBodies.get(4).contentLength() != 0) {
                        String result5 = responseBodies.get(4).string();
                        mySuccess(result5);
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            }

            @Override
            public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                Log.d("分发", "onError: " + e.getMessage());
            }
        });

        canDialog();
//        showToast(result);

    }

    private void mySuccess(String result) {
        //清楚数据

        runOnUiThread(() -> {
            //把成功的图片显示出来
            cl.setVisibility(View.VISIBLE);
            //关闭弹窗
            canDialog();
            //清除数据
            cleanData();
        });

//        showToast(result);

    }

    //提交方法，走接口
    private void submit() {

        Log.d("jjjjj", "stateId: " + stateId);
        Map<String, String> map = new HashMap<>();
        map.put("warehouseCode", infoBean.getWarehouseCode());
        map.put("status", stateId == null ? "" : stateId);
        map.put("idNo", decimalNumber + "");
        map.put("sncode", no);

        //先请求默认ip地址  失败重连另一个地址
        MyOkHttp.getInstance().post(submit, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                //提示重连
                runOnUiThread(() -> {
                    Toast.makeText(MainActivity.this, "Attempt to switch servers", Toast.LENGTH_SHORT).show();
                });
                //请求另外一个ip地址
                MyOkHttp.getInstance().post("http://192.168.1.96:8582/api/addCradData", map, new MyOkHttp.requestMessage() {
                    @Override
                    public void requestFail() {

                        //失败停止一秒  提示连接服务器失败
                        runOnUiThread(() -> {
                            try {
                                Thread.sleep(1000);
                            }catch (Exception e) {

                            }
                            Toast.makeText(MainActivity.this, "Failed to connect to server", Toast.LENGTH_SHORT).show();
                        });
                        //关闭弹窗
                        canDialog();

                    }

                    @Override
                    public void requestComplete() {

                    }

                    //成功逻辑  但是这个是重连服务的成功
                    @Override
                    public void requestSuccess(Response response) throws IOException {
                        runOnUiThread(() -> {
                            //把成功的图片显示出来
                            cl.setVisibility(View.VISIBLE);
                            //关闭弹窗
                            canDialog();
                            //清除数据
                            cleanData();
                        });
                    }
                });
            }

            @Override
            public void requestComplete() {

            }

            //当前ip的成功逻辑
            @Override
            public void requestSuccess(Response response) throws IOException {
                runOnUiThread(() -> {
                    //把成功的图片显示出来
                    cl.setVisibility(View.VISIBLE);
                    //关闭弹窗
                    canDialog();
                    //清除数据
                    cleanData();
                });
            }
        });

    }


    /**
     * 加载进度弹窗
     *
     * @param title 弹窗标题
     */
    public void showDialog(String title) {
        runOnUiThread(() -> {
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(this);
            }
            if (progressDialog.isShowing()) {
                return;
            }
            progressDialog.setTitle(title);
            progressDialog.setMessage("Loading...");
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
        });
    }


    //关闭弹窗
    public void canDialog() {
        if (progressDialog != null) {
            runOnUiThread(() -> progressDialog.cancel());
        }
    }


    // 定义 BroadcastReceiver 类
    private class TimeChangedReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
                // 获取当前时间
                String currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());

                String currentDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());

                // 更新 TextView 的文本
                tvTime.setText(currentTime);
                tvDate.setText(currentDate);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        serialControl.close();
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
//        unregisterReceiver(timeChangedReceiver);
    }


    public void initSerialHelper() {
        serialControl = new SerialControl();
        initRead();
    }

    class SerialControl extends SerialHelper {

        @Override
        protected void onDataReceived(final ComBean comBean) {

            runOnUiThread(new Runnable() {
                public void run() {
                    DispRecData(comBean);
                }
            });

        }


    }

    StringBuilder sMsg;

    private void DispRecData(SerialHelper.ComBean ComRecData) {

        if (sMsg == null) {
            sMsg = new StringBuilder();
        }


        byte[] bytes = ComRecData.bytes;

        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));  // 将每个字节转换为两位的十六进制字符串
        }
        String hexString = sb.toString();  // 获取十六进制字符串
        Log.d("这个是卡号", "no16: " + hexString);
        String middlePart1 = hexString.substring(8, hexString.length() - 8);
        String middlePart2 = hexString.substring(10, hexString.length() - 6);
        String middlePart3 = hexString.substring(12, hexString.length() - 4);

        String car16 = middlePart3 + middlePart2 + middlePart1;
        Log.d("这个是卡号", "no16ss: " + car16);
        decimalNumber = Long.parseLong(car16, 16);

        BigInteger decimal = new BigInteger(hexString, 16);  // 将十六进制字符串转换为十进制数值
        sMsg.setLength(0);
        sMsg.append(byteArrToHex);
        byteArrToHex = String.valueOf(decimal);
        Log.d("这个是卡号", "no: " + decimalNumber);
        MyEquals(decimalNumber + "");


    }

    private void MyEquals(String sMsg) {
        showDialog("card swiping...");
        post(sMsg, no);
    }

    private void initRead() {


        serialControl.setPort("/dev/ttyUSB0");
        serialControl.setBaudRate("38400");
        File file = new File("/dev/ttyUSB0");
        try {
            serialControl.open();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!file.canRead() || !file.canWrite()) {
            return;
        }

    }

    private void showToast(String message) {

        runOnUiThread(() ->  Toast.makeText(this, message, Toast.LENGTH_SHORT).show());


    }

}
